/**
 * @param {number[][]} matrix
 * @return {number[]}
 */
var spiralOrder = function (matrix) {
  if (matrix.length === 0) return []

  let res = []
  let top = 0
  let right = matrix[0].length - 1
  let bottom = matrix.length - 1
  let left = 0

  while (top <= bottom && left <= right) {
    //向右遍历
    for (let i = left; i <= right; i++) {
      res.push(matrix[top][i])
    }
    //调整边界
    top++
    //调整边界后检查是否越界
    if (top > bottom) break

    //向下遍历
    for (let i = top; i <= bottom; i++) {
      res.push(matrix[i][right])
    }
    //调整边界
    right--
    //调整边界后检查是否越界
    if (right < left) break

    //向左遍历
    for (let i = right; i >= left; i--) {
      res.push(matrix[bottom][i])
    }
    //调整边界
    bottom--
    //调整边界后检查是否越界
    if (bottom < top) break

    //向上遍历
    for (let i = bottom; i >= top; i--) {
      res.push(matrix[i][left])
    }
    //调整边界
    left++
    //调整边界后检查是否越界
    if (left > right) break
  }

  return res
};